//
//  MYRefreshControl.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/19.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

import UIKit
let refreshHeight: CGFloat = 60
//枚举记录状态
enum MYRefreshStatus: Int {

    case Normal     = 0     //普通状态
    case Pulling    = 1     //准备刷新状态
    case Refreshing = 2     //刷新状态
    
}
class MYRefreshControl: UIControl {
    //刷新视图所在的状态
    var status: MYRefreshStatus = .Normal {
        //根据状态刷新UI界面
        didSet {
            switch status {
            case .Normal:
                tipLabel.text = "下拉刷新"
                
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollview!.contentInset
                        inset.top = inset.top - refreshHeight
                        self.scrollview?.contentInset = inset

                    })
                }
                //停止转动小菊花
                indicatorView.stopAnimating()
                //显示箭头
                arrowicon.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
            case .Pulling:
                tipLabel.text = "松手刷新"
                //旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                tipLabel.text = "正在加载..."
                //转动小菊花
                indicatorView.startAnimating()
                //隐藏箭头
                arrowicon.hidden = true

                //等待刷新数据 数据刷新成功后 改为普通状态
                //主动给当前的对象发送对应的事件类型 会自动找到对应的target 调用监听的方法
                sendActionsForControlEvents(.ValueChanged)
                
                //修改contentInSet的top
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollview!.contentInset
                    inset.top = inset.top + refreshHeight
                    self.scrollview?.contentInset = inset
                    
                })
            }
        }
    }
    
    func endRefreshing() {
    
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.9))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.status = .Normal
        }
        
    }

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //reason: '<MYWeibo.MYRefreshControl: 0x7fbbe38450a0; baseClass = UIControl; frame = (0 -60; 375 60); layer = <CALayer: 0x7fbbe15c3fb0>>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
    //发出的通知没有接收对象
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //print(change)
        //实时获取父视图的垂直方向的位移 和 -124比较 修改视图的状态
        let offsetY = scrollview?.contentOffset.y
        
        let targetOffsetY = -scrollview!.contentInset.top - refreshHeight
        //需要检测用户是否正在拖拽
        if scrollview!.dragging {
            if status == .Pulling && offsetY > targetOffsetY {
                //print("普通状态")
                status = .Normal
            }else if status == .Normal && offsetY < targetOffsetY {
                //print("准备刷新状态")
                status = .Pulling
            }
        }else {
            //没有拖拽 并且是准备刷新状态
            if status == .Pulling {
                //print("正在刷新状态")
                status = .Refreshing
            }
        }
    }
    
    //视图将要移动到父视图上的时候调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //获取父视图
        if let myFather = newSuperview as? UIScrollView {
            
            //记录观察对象
            self.scrollview = myFather
            
            //实时获取滚动视图垂直方向的位移
            /*
            observer: 要添加的观察者
            forKeyPath: 要观察的键值属性
            options:
            context:
            */
            
            //KVO  作用: 观察对象的属性变化
            myFather.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        }
    }
    
    //MARK: 设置UI界面
    private func setupUI() {
        //backgroundColor = UIColor.redColor()
        
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        
        arrowicon.snp_makeConstraints { (make) -> Void in
            //水平居中 向左偏移 30
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }

        
    }
    
    //记录观察对象
    private var scrollview: UIScrollView?
    
    //懒加载子视图
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(text: "下拉起飞", textColor: UIColor.darkGrayColor(), fontSize: 14)
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

    //移除观察对象
    deinit {
    
        scrollview?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
